package com.ruoyi.business.controller.imagecontroller;

import org.apache.velocity.shaded.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
public class ImageController {

    @Autowired
    private ImageService imageService;

    @PostMapping("business/user/upload")
    public String handleFileUpload(@RequestParam("File") MultipartFile file) {
        try {
            String originalFileName = file.getOriginalFilename();
            String baseName = FilenameUtils.getBaseName(originalFileName);//文件名
            String extension = FilenameUtils.getExtension(originalFileName);//后缀
            byte[] bytes = file.getBytes();
            UUID uuid = UUID.randomUUID();


            Path path = Paths.get("D:\\ruoyi\\uploadPath\\upload\\" + baseName+"."+extension);
            Files.write(path, bytes);
            System.out.println(uuid.toString()+baseName+"."+extension);
            return baseName;
        } catch (IOException e) {
            e.printStackTrace();
            return "File upload failed";
        }
    }

    @GetMapping("/images")
    public ResponseEntity<Resource> getImage(@PathVariable String imageName) {
        org.springframework.core.io.Resource resource = imageService.loadImageAsResource(imageName);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(resource);
    }
}
